<?php
/**
 * Simple Light PHP Framework
 *
 * @copyright Marc PEPIN 2012
 * @author Marc PEPIN
 *
 */

defined('SLP_ROOT') or die("You've not access to this page");
 
/** 
* Simple Light Php Framework Logger Class
* @package		Slp
* @author    	Marc PEPIN
*/ 

class Slp_Logger {
	
	/**
	* @var $stringFormat default error output format 
	*/
	
	
	private $stringFormat = "#t on line #l in file #f: #s";
	
	
	/**
	* Constructor
	*/
	
	public function __construct() {
		set_error_handler(array($this, 'handler'));
	}
	
	
	/**
	* Save new error in log
	* @param object
	*/
	
	private function save($errorInfo) {
		$file = Slp::getInstance()->loadClass('Slp_File', array(SLP_ROOT.'/application/logs/application.log', true));
		$data = $file->readAll();
		if (!$data) {
			$logs = array($errorInfo);
			$file->write(serialize($logs));	
		}
		else
		{
			$data = unserialize($data);
			$data[] = $errorInfo;
			$file->write(serialize($data));	
		} 
	}
	
	
	/**
	* format object error
	* @param stdClass
	* @ret string
	*/
	
	private function format($errorInfo) {
		$subjects= array(
							'!(#t)!' => $errorInfo->type,
							'!(#l)!' => $errorInfo->line,
							'!(#f)!' => $errorInfo->file,
							'!(#s)!' => $errorInfo->str
					);
		$format = $this->stringFormat;
		foreach($subjects as $pattern => $replace)
			$format = preg_replace($pattern, $replace, $format);
		return $format;
	}
	
	
	/**
	* Last error in log
	* @ret string
	*/
	
	public function lastError() {
		$file = Slp::getInstance()->loadClass('Slp_File', array(SLP_ROOT.'/application/logs/application.log', true));
		$data = $file->readAll();
		$data = unserialize($data);
		if ($data)
			return $this->format($data[count($data) - 1]);
		return NULL;
	}
	
	
	/**
	* Custom error handler
	* @param int
	* @param string
	* @param string
	* @param int
	* @param array
	*/
	
	public function handler($errno , $errstr , $errfile , $errline , $errctx) {
		
		$errorInfo = new stdClass;
		$errorInfo->no = $errno;
		$errorInfo->str = $errstr;
		$errorInfo->file = $errfile;
		$errorInfo->line = $errline;
		//$errorInfo->ctx = $errctx; 
		
		switch ($errno) {
			case E_USER_ERROR:
			$errorInfo->type = "Critical Error";
			break;
			
			case E_USER_WARNING:
			$errorInfo->type = "Warning";
			break;
			
			case E_USER_NOTICE:
			$errorInfo->type = "Notice";
			break;
			
			default:
			$errorInfo->type = "Unknow error";
			break;
		}
		
		$this->save($errorInfo);
		return true;
		
	}
}
	
?>